﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class CameraUtil
{
    /// <summary>
    /// 对相机进行截图
    /// </summary>
    public static Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        CameraClearFlags flag = camera.clearFlags;
        camera.clearFlags = CameraClearFlags.SolidColor;
        RenderTexture rt = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 0);
        camera.targetTexture = rt;
        camera.Render();
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注：这个时候，它是从RenderTexture.active中读取像素
        screenShot.Apply();

        camera.clearFlags = flag;
        camera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);

#if UNITY_EDITOR || UNITY_STANDALONE
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));
#endif

        return screenShot;
    }

}
